<?php
/**
 * @category   Application_Extensions
 * @package    Talktangle Plugin 
 * @copyright  Idragon Co., Ltd.
 * @license
 */
class Talktangle_Widget_CreatetalktangleController extends Engine_Content_Widget_Abstract {
		
	public function indexAction() {
	
        $request = Zend_Controller_Front::getInstance()->getRequest();
        
        $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();
        $this->view->form = $form = new Talktangle_Form_Talktangle_Create();
        
		$request = Zend_Controller_Front::getInstance()->getRequest();
		$tangle_id = $request->getParam('tangle',null);    
        
        if(!empty($tangle_id)){
            return $this->editAction($tangle_id);
        }        
           
        // Check post
        if(!$this->getRequest()->isPost()){
            return;
        }
        $this->view->isValidF = true;
        // Check form validate
        if(!$form->isValid($this->getRequest()->getPost())){
            $this->view->isValidF = false;
            return;
        }
        $values = $form->getValues();   
//        print_r($values); die;
        $table = Engine_Api::_()->getDbTable('talktangles','talktangle');
    
        //save form values
        $db = $table->getAdapter();
        $db->beginTransaction();
        try
        {            
            $talktangle = $table->createRow();
            $talktangle->setFromArray($values);
            $talktangle->owner_id = $viewer->getIdentity();
            $talktangle->type = $viewer->type;
            if (isset($values['post_facebook'])) {
                $talktangle->facebook = $values['post_facebook'];
            }
            if (isset($values['post_tiwtter'])) {
                $talktangle->tiwtter = $values['post_tiwtter'];
            }
            
            
            $durationUser = Engine_Api::_()->getApi('settings','core')->getSetting('talktangle.user.duration',60*10);
            $talktangle->duration = time()+$durationUser;

            $talktangle->save();
            
            $point =  Engine_Api::_()->getApi('settings', 'core')->getSetting('talktangle.point', 2);
            $viewer->points = $viewer->points + $point;
            $viewer->tangle = $viewer->tangle + 1;
            $viewer->save();
            $db->commit();   
                   
            $form->addNotice($this->view->translate('Your talktangle created successfully.'));                       
            
//            die;       
//            $this->view->success = true;                    
        }
        catch(Exception $e)
        {
            $db->rollBack();
            throw $e;
        }  
        
        $ads = null;
        
        //copmany type
        //Add adv, promotion, duration
        if($viewer->type == 'company'){
                       
            if(!empty($values['pro_title'])||!empty($values['pro_description'])){
                //add value to promotion
                $promotiontable = Engine_Api::_()->getDbTable('promotions','talktangle');
                //save form values
                $db = $promotiontable->getAdapter();
                $db->beginTransaction();
                try
                {            
                    $promotion = $promotiontable->createRow();
                    $promotion->owner_id = $viewer->getIdentity();
                    
                    if($values['pro_title']){
                        $promotion->title = $values['pro_title'];          
                    } 
                    if($values['pro_description']){
                        $promotion->description = $values['pro_description'];         
                    }           
                    
                    if(!empty($values['pro_file_id'])){
                        $file_id = $values['pro_file_id'];  
                        $promotion->photo_id = $file_id;          
                    }         
                                                          
                    $promotion->save();  
                    
                    //update promotion_id in talktangle
                    $talktangle->promotion_id = $promotion->promotion_id;
                    $talktangle->save();
                              
                    $db->commit();   
                }
                catch(Exception $e)
                {
                    $db->rollBack();
                    throw $e;
                }    
            }
//            
            //add value to ads
            if(!empty($values['ads_title'])||!empty($values['ads_description'])||!empty($values['file_id'])){
                $adsTable = Engine_Api::_()->getDbTable('ads','talktangle');
                //save form values
                $db = $adsTable->getAdapter();
                $db->beginTransaction();
                try
                {                     
                    $ads = $adsTable->createRow();
                    
                    $ads->owner_id = $viewer->getIdentity();
                    if(!empty($values['ads_title'])){
                        $ads->title = $values['ads_title'];      
                    }    
                    if(!empty($values['ads_description'])){
                        $ads->description = $values['ads_description'];           
                    }                  
//                    echo "<pre>";
//                    print_r($values); die;  
                    if(!empty($values['file_id'])){
                        $file_id = $values['file_id'];  
                        $ads->photo_id = $file_id;          
                    }         
                
                    $ads->save(); 
                    
                    //update ads_id in talktangle
                    $talktangle->ad_id = $ads->ad_id;
                    $talktangle->save();
                                
                    $db->commit();      
                    return $this->continueProcessBuy($talktangle,'talktangle',$ads, $form);
                }          
                catch(Exception $e)
                {
                    $db->rollBack();
                    throw $e;
                } 
            }
        }             

//        if($viewer->type =='company' && $ads){
//            
//        }
//        else{
            
            $actionT = Engine_Api::_()->getDbtable('actions','activity');
            $actionT->addActivity($viewer, $talktangle ,'post_talktangle');
            $this->view->url = $url =  Zend_Controller_Front::getInstance()->getRouter()
                    ->assemble(array('controller'=>'index','action'=>'index'), 'talktangle_extended', true);
                    
            $core = Engine_Api::_()->talktangle();
            if ( !empty($_POST['post_facebook']) && $core->enableFacebook() ) {
                $params = array(
                    'body' => 'had post new crosstangle '.$talktangle->title,
                    'link' => 'http://' . $_SERVER['HTTP_HOST'].$talktangle->getHref()
                     
                );
               
                $core->postFacebook($params);
            }
            if ( !empty($_POST['post_tiwtter'])  && $core->enableTiwtter()) {
                $params = array(
                    'body' => 'had post new crosstangle '.$talktangle->title,
                    'link' => 'http://' . $_SERVER['HTTP_HOST'].$talktangle->getHref()
                     
                );
                $core->postTwitter($params);
            }
                
            header("Location: $url"); 
//        }                 
	}
    
    
    protected function continueProcessBuy($tangle,$type,$ads,$form) {
    	
        $user = Engine_Api::_()->user()->getViewer();
        // Get gateway
        $gatewayId = 2;	//Always is PayPay
        if( !$gatewayId ||
                !($gateway = Engine_Api::_()->getItem('payment_gateway', $gatewayId))
               ) {
            return $form->addError(Zend_Registry::get('Zend_Translate')->_('Paypal is disabled. Please contact to administrator for more details'));
        }
        $this->view->gateway = $gateway;

		if(!($gateway->enabled)){
			return $form->addError(Zend_Registry::get('Zend_Translate')->_('Paypal is disabled. Please contact to administrator for more details'));
		}
    		
		//Get Currency of Groupon
		$paypalConfig = (array)$gateway->config;
        $paypalConfig['testMode'] =  $gateway->test_mode;

    	$plugin =  new Talktangle_Plugin_Gateway_PayPal((array)$paypalConfig);        

        // Create order
        $ordersTable = Engine_Api::_()->getDbtable('orders', 'payment');
        if( !empty($this->_session->order_id) ) {
            $previousOrder = $ordersTable->find($this->_session->order_id)->current();
            if( $previousOrder && $previousOrder->state == 'pending' ) {
                $previousOrder->state = 'incomplete';
                $previousOrder->save();
            }
        }

        $ordersTable->insert(array(
                'user_id' => Engine_Api::_()->user()->getViewer()->getIdentity(),
                'gateway_id' => $gateway->gateway_id,
                'state' => 'pending',
                'creation_date' => new Zend_Db_Expr('NOW()'),
                'source_type' => 'talktangle_ads',
                'source_id' => $ads->ad_id,
        ));
        $this->_session->order_id = $order_id = $ordersTable->getAdapter()->lastInsertId();
		
        // Prepare host info
        $schema = 'http://';
        if( !empty($_ENV["HTTPS"]) && 'on' == strtolower($_ENV["HTTPS"]) ) {
            $schema = 'https://';
        }
        $host = $_SERVER['HTTP_HOST'];
        
        
        $params = array();
        $params['language'] = $user->language;
        $localeParts = explode('_', $user->language);
        if( count($localeParts) > 1 ) {
            $params['region'] = $localeParts[1];
        }
        $params['vendor_order_id'] = md5($order_id. $ads->title);
        $params['return_url'] = $schema . $host
                . $this->view->url(array('controller'=>'talktangle','action'=>'paypalreturn', 'module'=>'talktangle'),'default',true)
                . '?order_id=' . $order_id
                . '&state=' . 'return'
                . '&tangle_id='. $tangle->getIdentity()
                . '&type='.$type;
        $params['cancel_url'] = $schema . $host
                . $this->view->url(array('controller'=>'talktangle','action'=>'paypalreturn', 'module'=>'talktangle'),'default',true)
                . '?order_id=' . $order_id
                . '&state=' . 'cancel'
                . '&tangle_id='. $tangle->getIdentity()
                . '&type='.$type;

        //Sell Now Value
        $params['price'] = floatval(5);

        $params['description'] = 'sale';
        $params['amount'] = 1;
        // Process transaction
        $talktangleCore = Engine_Api::_()->talktangle();
        $transaction = $talktangleCore->createBuyNowTransaction($plugin, $ads, $params);
        // Pull transaction params
        $this->view->transactionUrl = $transactionUrl = $plugin->getGateway()->getGatewayUrl();
        $this->view->transactionData = $transactionData = $transaction->getData();
        // Handle redirection
        $transactionUrl .= '?cmd=_express-checkout&token=' . $transactionData['token'];

        // Redirect to paypal
        //return $this->_helper->redirector->gotoUrl($transactionUrl, array('prependBase' => false));
        header("Location: $transactionUrl"); 
    }  
    
    public function editAction($tangle_id){
        
        $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();
        $this->view->form = $form = new Talktangle_Form_Talktangle_Create();
                
        $talktangle = Engine_Api::_()->getItem('talktangle',$tangle_id);
        $form_values = $talktangle->toArray();
        if(!empty($talktangle->promotion_id)){
            $promotion = Engine_Api::_()->getItem('talktangle_promotion',$talktangle->promotion_id);
            $form_values = array_merge($form_values,array(
                    'pro_title' => $promotion->title,
                    'pro_description' => $promotion->description,
                ));
        }   
        if(!empty($talktangle->ad_id)){
            $ads = Engine_Api::_()->getItem('talktangle_ad',$talktangle->ad_id);
            $form_values = array_merge($form_values,array(
                    'ads_title' => $ads->title,
                    'ads_description' => $ads->description,
                ));
        }   
                                    
        $form->populate($form_values);  
        
        // Check post
        if(!$this->getRequest()->isPost()){
            return;
        }
        // Check form validate
        if(!$form->isValid($this->getRequest()->getPost())){
            return;
        }
        $values = $form->getValues(); 

        // Process
        $db = Engine_Db_Table::getDefaultAdapter();
        $db->beginTransaction();       
        try
        {            
            $talktangle->setFromArray($values);
            $talktangle->save();
            $db->commit();      
//            die;       
//            $this->view->success = true;                    
        }
        catch(Exception $e)
        {
            $db->rollBack();
            throw $e;
        }

        if(!empty($values['pro_title'])||!empty($values['pro_description'])){
            // Process
            $db = Engine_Db_Table::getDefaultAdapter();
            $db->beginTransaction();       
            try
            {                   
                $promotion = Engine_Api::_()->getItem('talktangle_promotion',$talktangle->promotion_id);

                if($values['pro_title']){
                    $promotion->title = $values['pro_title'];      
                }    
                if($values['pro_description']){
                    $promotion->description = $values['pro_description'];           
                }                  
            
                $promotion->save(); 

                $db->commit();      
            }          
            catch(Exception $e)
            {
                $db->rollBack();
                throw $e;
            }           
        }
        
        if(!empty($values['ads_title'])||!empty($values['ads_description'])||!empty($values['file_id'])){
            // Process
            $db = Engine_Db_Table::getDefaultAdapter();
            $db->beginTransaction();       
            try
            {                   
                $adsTable = Engine_Api::_()->getDbTable('ads','talktangle');
                $ads = $adsTable->createRow();
                
                $ads->owner_id = $viewer->getIdentity();
                if($values['ads_title']){
                    $ads->title = $values['ads_title'];      
                }    
                if($values['ads_description']){
                    $ads->description = $values['ads_description'];           
                }                  
                      
                if(!empty($values['file_id'])){
                    $file_id = $values['file_id'];  
                    $ads->photo_id = $file_id;          
                }         
            
                $ads->save(); 
                
                //update ads_id in talktangle
                $talktangle->ad_id = $ads->ad_id;
                $talktangle->save();
                            
                $db->commit();      
                return $this->continueProcessBuy($talktangle,'talktangle',$ads, $form);
            }          
            catch(Exception $e)
            {
                $db->rollBack();
                throw $e;
            }                          
        }
        else{
            // if no ads
            $talktangle->payment_status = 0;
        }
        

        if($viewer->type =='company' && $ads){
            
        }
        else{
            
            $actionT = Engine_Api::_()->getDbtable('actions','activity');
            $actionT->addActivity($viewer, $talktangle ,'post_talktangle');
            $this->view->url = $url =  Zend_Controller_Front::getInstance()->getRouter()
                    ->assemble(array('controller'=>'index','action'=>'index'), 'talktangle_extended', true);
            header("Location: $url"); 
        }                            
    }
}